<template>
  <div class="table_list_fix">
    <!-- 扩展性内容 -->
    <slot name="content_context" />
    <el-table
      ref="multipleTable"
      border="border"
      use-virtual
      v-loading="tableLoading"
      :data="dataSource"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectChange"
      :height="400"
    >
      <el-table-column
        fixed
        type="selection"
        width="50"
        :selectable="handleSelectable"
      />
      <el-table-column
        v-for="column in columns"
        :key="column.key"
        :prop="column.key"
        :label="column.title"
        :property="column.key"
        :align="column.align"
        :min-width="column.width || 120"
        :fixed="column.fixed"
        :formatter="column.formatter"
        :show-overflow-tooltip="true"
      >
        <template v-if="column.render" v-slot="scope">
          <table-column
            :index="scope.$index"
            :row="scope.row"
            :col="scope.column"
            :render="column.render"
          />
        </template>
        <template v-else-if="column.type === 'radioSelect'" v-slot="scope">
          <template v-if="!getReferenceCityStatusFn(scope.row)">
            <span>{{ scope.row.templateCityName }}</span>
          </template>
          <template v-else>
            <el-select
              v-if="referenceCityList.length !== 0"
              v-model="scope.row.templateCityUuid"
              placeholder="请选择"
              @change="(val) => {handleChooseReferenceCity({ val, row: scope.row, index: scope.$index, })}"
            >
              <el-option
                v-for="item in referenceCityList"
                :disabled="item._disabled"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </template>
        <template v-else-if="column.key === 'buyPriceRatio'" v-slot="scope">
          <template v-if="isNotMaintainByBuyRatio(scope.row)">
            <span>无需维护</span>
          </template>
          <template v-else>
            <input-number v-model="scope.row.buyPriceRatio" controls-position="right" />
          </template>
        </template>
        <template v-else-if="column.key === 'costPriceRatio'" v-slot="scope">
          <template v-if="isNotMaintainByCostRatio(scope.row)">
            <span>无需维护</span>
          </template>
          <template v-else>
            <input-number v-model="scope.row.costPriceRatio" controls-position="right" />
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { ApiRequest } from '@api/basePage';
import tableColumn from './tableColumn';
import inputNumber from '@/components/inputNumber/inputNumber';
import { mapState, mapMutations } from 'vuex';

export default {
  name: 'BasicList',
  /**
   *@columns 表格列表columns
   *如果爷组件有不同于此表格组件默认的columns，则需要在爷组件provide新columns，如下所示
   * provide () {
      return {
        columns: 【
          {
            title: '销售城市',
            key: 'saleCityName',
            width: 90,
            align: 'center'
          },...
        】
      }
    },
  */
  inject: {
    columns: {
      default: () => [
        {
          title: '销售城市',
          key: 'saleCityName',
          width: 90,
          align: 'center'
        },
        {
          title: '销售省',
          key: 'saleProvinceName',
          width: 90,
          align: 'center'
        },
        {
          title: '是否供货',
          slot: 'isSupply',
          width: 90,
          render: (h, { row }) => {
            return <span>{row.isSupply === '1' ? '是' : '否'}</span>;
          }
        },
        {
          title: '业务区域',
          key: 'areaName',
          width: 120,
          align: 'center'
        },
        {
          title: '参照城市',
          key: 'templateCityName',
          width: 150,
          type: 'radioSelect'
        },
        {
          title: '进价比例',
          key: 'buyPriceRatio',
          width: 160
        },
        {
          title: '成本价比例',
          key: 'costPriceRatio',
          width: 160
        }
      ]
    }
  },
  components: {
    tableColumn,
    inputNumber
  },
  props: {
    /**
     *@checkedCityCodeList 已选择的表格行数据的cityCode集合
     */
    border: { type: Boolean, default: true },
    // 是否手动
    isHandleCheck: { type: Boolean, default: false },
    checkedCityCodeList: {
      type: Array,
      default () {
        return [];
      }
    }
  },
  data () {
    return {
      tableLoading: true, // 表格loading
      theTimer: '', // 定时器
      handleChecked: false
    };
  },
  mounted () {
    this.$nextTick(() => {
      this.$emit('toggleRowSelection', this.$refs.multipleTable);
      /* 当弹框关闭时，初始化loading状态，同时清除定时器 */
      this.$on('destoryTimerEvent', () => {
        this.tableLoading = true;
        clearTimeout(this.theTimer);
      });
    });
  },
  computed: {
    ...mapState('commonComps/setReferenceCity', [
      'dataSource',
      'referenceCityList',
      'purchasePriceType',
      'historyCityList'
    ]),
  },
  watch: {
    isHandleCheck: {
      immediate: true,
      handler (val) {
        this.handleChecked = val;
      }
    },
    checkedCityCodeList: {
      immediate: true,
      handler (newVal) {
        /* 为防止数据渲染慢于初始渲染造成的卡顿，加1秒loading用来缓冲 */
        this.theTimer = setTimeout(() => {
          if (this.purchasePriceType === '1') {
            this.unifiedPurchaseInteractionFn(newVal);
          } else {
            this.areaPurchaseInteractionFn(newVal);
          }
          this.tableLoading = false;
        }, 100);
      }
    },
  },
  methods: {
    ...mapMutations('commonComps/setReferenceCity', [
      'SET_TABLE_DATA',
      'SET_REFERENCE_CITIES',
      'SET_SELECTED_ITEM',
      'SET_DEFAULT_REFERENCE_CITIES'
    ]),
    /* 表格checkbox禁用与否状态 */
    handleSelectable (row, index) {
      /*
        返回true，表格可勾选
        返回false，表格不可勾选
      */
      // if (row.isSupply === '1' && this.purchasePriceType === '1') {
      //   return false;
      // } else {
      //   return true;
      // }
      if (this.purchasePriceType == '1' && row.saleCityNo == row.templateCityUuid) return false
      return true
    },
    /* 统一进价交互逻辑处理 */
    unifiedPurchaseInteractionFn (sourceList) {
      let tableData = _.cloneDeep(this.dataSource);
      tableData.forEach((row) => {
        // row.templateCityName = row.templateCityName ? row.templateCityName : '';
        // row.templateCityUuid = row.templateCityUuid ? row.templateCityUuid : '';
        if (!sourceList.includes(row.saleCityNo)) {
          row.isSupply = '2';
        } else {
          row.isSupply = '1';
          row._disabled =
            this.purchasePriceType === '1';
        }
      });
      let referenceCityList = tableData.reduce((value, item) => {
        value.push({
          _disabled: item.isSupply !== '1',
          value: item.saleCityNo,
          label: item.saleCityName
        });
        return value;
      }, []);
      let defaultReferenceCityList = tableData.filter((item) => {
        return item.isSupply === '1';
      }).map(item => ({
        ...item,
        templateCityName: item.saleCityName,
        templateCityUuid: item.saleCityNo
      }));
      this.SET_TABLE_DATA(tableData);
      this.SET_REFERENCE_CITIES(referenceCityList);
      this.SET_DEFAULT_REFERENCE_CITIES(defaultReferenceCityList);
    },
    /* 区域进价交互逻辑处理 */
    areaPurchaseInteractionFn (sourceList) {
      let tableData = _.cloneDeep(this.dataSource);
      let referenceCityList = _.cloneDeep(this.referenceCityList);
      tableData.forEach((row) => {
        let index = _.findIndex(referenceCityList, (item) => {
          return item.value === row.saleCityNo;
        });
        if (!sourceList.includes(row.saleCityNo)) {
          referenceCityList[index]._disabled = true;
          row.templateCityName = '';
          row.templateCityUuid = '';
          row.buyPriceRatio = null;
          row.costPriceRatio = null;
          row.isSupply = '2';
        } else {
          referenceCityList[index]._disabled = false;
          row.isSupply = '1';
          // 当前行数据的参照城市 不在供货城市内
          if (!sourceList.includes(row.templateCityUuid)) {
            row.templateCityName = row.saleCityName;
            row.templateCityUuid = row.saleCityNo;
          }
          if (!this.handleChecked && this.historyCityList && this.historyCityList.length > 0) {
            this.historyCityList.forEach(({ saleCityNo, templateCityUuid, buyPriceRatio, costPriceRatio }) => {
              if (row.saleCityNo == saleCityNo) {
                row.templateCityName = this.list2Obj(this.referenceCityList)[Number(templateCityUuid)];
                row.templateCityUuid = templateCityUuid;
                row.buyPriceRatio = buyPriceRatio;
                row.costPriceRatio = costPriceRatio;
              }
            })
          }
        }
      });
      this.SET_TABLE_DATA(tableData);
      this.SET_REFERENCE_CITIES(referenceCityList);
    },
    /* 下拉选择参照城市 */
    handleChooseReferenceCity (data) {
      /* 单独选择参照城市的时候，需要同步参照城市的城市名称 */
      let { val, row } = data;
      let target = _.find(this.referenceCityList, (item) => {
        return item.value === val;
      });
      row.templateCityName = target.label || '';
      if (row.isSupply === '1') {
        return;
      }
      /* 如果销售城市不供货，则需要调用获取成本价比例接口更新成本价比例 */
      this.getCostPriceRatioByAreaCodeAction(data).then((res) => {
        if (!res) {
          return;
        }
        row.buyPriceRatio = res[0].buyPriceRatio || 1;
        row.costPriceRatio = res[0].costPriceRatio;
      });
    },
    /* 获取成本价比例 */
    getCostPriceRatioByAreaCodeAction (data) {
      let { row, val, notSupplyCityList } = data;
      let params = notSupplyCityList || [
        { saleCityUuid: row.saleCityNo, templateCityUuid: val }
      ];
      return new Promise((resolve, reject) => {
        this.tableLoading = true;
        ApiRequest(
          '/sysback/supplyinfopriceratio/getPriceRatioByAreaCode',
          'post',
          params
        )
          .then((res) => {
            this.tableLoading = false;
            if (res.retStatus !== '1') {
              return;
            }
            resolve(res.retData);
          })
          .catch((err) => {
            this.tableLoading = false;
            reject(err);
          });
      });
    },
    /* 参照城市状态维护 */
    getReferenceCityStatusFn (row) {
      /**
       * 返回true表示需要维护，false不需要维护
       * @isSupply 是否供货状态，1为供货，2为不供货
       * @purchasePriceType 进价类别，1为统一进价 2为区域进价
       */
      if (this.purchasePriceType === '1') {
        return false;
      }
      return true;
    },
    // 进价比例无需维护
    isNotMaintainByBuyRatio (row) {
      if (this.purchasePriceType === '1') { // 是统一进价
        row.buyPriceRatio = 1;
        return true;
      }
      if (row.isSupply === '1' && row.templateCityUuid === row.saleCityNo) { // 可以供货，且自己参照自己
        row.buyPriceRatio = 1;
        return true;
      }
    },
    // 成本价比例无需维护
    isNotMaintainByCostRatio (row) {
      if (row.isSupply === '1' && row.templateCityUuid === row.saleCityNo) { // 可以供货，且自己参照自己
        row.costPriceRatio = 1;
        return true;
      }
    },
    /* 勾选表格row */
    handleSelectChange (data) {
      this.SET_SELECTED_ITEM(data);
    },
    list2Obj (list = []) {
      const obj = {}
      if (list && list.length) {
        list.forEach(({ value, label }) => {
          obj[value] = label
        });
      }
      return obj
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-table thead.is-group th {
  background: #fff;
}
</style>
